package alex.rsx.activity;
import alex.rsx.activity.r.R;
import alex.rsx.reader.OnCmdListener;
import alex.rsx.reader.ReaderBook;
import alex.rsx.reader.ReaderConfig;
import alex.rsx.reader.ReaderSet;
import alex.rsx.view.DiffuseView;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.alex.books.BaseBook;
import com.alex.books.BookPageFactory;
import com.alex.books.BookStore;
import com.alex.database.BookDao;
import com.alex.exception.UnsupportedFormatException;


public class ReadBookActivity extends BaseActivity implements OnClickListener, OnCmdListener,android.content.DialogInterface.OnClickListener{
	public static String BOOK_ID = "book_id";
	public static String READINGINFO = "readinginfo";
	
	//阅读书本
	private BaseBook mBaseBook;
	//阅读器
	private ReaderBook mReader;
	//
	//阅读屏幕的宽度
	private int mScreenW;
	//阅读屏幕的高度
	private int mScreenH;
	//屏幕的密度
	private float mDensity;
	
	private int msgWhat = 0;
	private Handler mHandler =  new Handler() { 
		public void handleMessage(Message msg) {  
			
			switch (msg.what) {
			case -1:
				Toast.makeText(ReadBookActivity.this, "不好意思，不支持格式", Toast.LENGTH_SHORT).show();
				break;
			case 0:
				mReader.setLineSpace(ReaderSet.getInstance().getmFontSize()*mDensity);
				mReader.setReaderTextSize(ReaderSet.getInstance().getmFontSize(),mDensity);
				mReader.setTypeface();
				mReader.nextPage();
				mReader.onFirst();
				break;
			case 1:
				mReader.setLineSpace(ReaderSet.getInstance().getmFontSize()*mDensity);
				mReader.setReaderTextSize(ReaderSet.getInstance().getmFontSize(),mDensity);
				mReader.setTypeface();
				mReader.setReaderDir(ReaderConfig.READMODE.get(1).mKey);
				mReader.reFreshPage();
				break;
			default:
				break;
			}
            super.handleMessage(msg);   
       }   
	};
	
	private class mThread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				BaseBook base = new BaseBook();
				base.mIsFirstReader = 1;
				base.mBookPath = "/sdcard/sd/test_s.txt";
				base.mBookSerial = "reer";
				mBaseBook = base;
				BookPageFactory.getInstance().openBook(ReadBookActivity.this,mBaseBook);
				BookPageFactory.getInstance().setReaderFormat(ReaderSet.getInstance().getmFontSize()*mDensity, 0, mScreenW - 40, mScreenH-45);
				mHandler.sendEmptyMessage(msgWhat);
			} catch (UnsupportedFormatException e) {
				// TODO Auto-generated catch block
				mHandler.sendEmptyMessage(-1);
				e.printStackTrace();
			}
		}
	}
	
	private DiffuseView mDiffuseView;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_reader);
        ReaderSet.getInstance().init(this);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenW = metric.widthPixels;  // 屏幕宽度（像素）
        mScreenH = metric.heightPixels;  // 屏幕高度（像素）
        mDensity = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）
        
        //初始化组件
        initFindView();
        //初始化设置（阅读设置和加载图书）
        initReaderSet();
        //进入全屏
        changeReadModel();
        mDiffuseView = (DiffuseView)findViewById(R.id.readoperation);
        mDiffuseView.setVisibility(View.GONE);
	}
	
	/**
	 * 初始化设置
	 */
	private void initReaderSet(){
		
	     WindowManager.LayoutParams lp = ReadBookActivity.this.getWindow().getAttributes();  
	 	 lp.screenBrightness = Float.valueOf(ReaderSet.getInstance().getBrightness()) *1 / 255;
	 	 this.getWindow().setAttributes(lp); 
	 	 msgWhat = 0;
	     initBookPageFactory();
	}
	
	/**
	 * 初始化
	 */
	private void initFindView(){
		mReader = (ReaderBook)findViewById(R.id.reader);
	    mReader.setOnSingleTapUpListener(this);
		mReader.init(mScreenW, mScreenH, mDensity);
	}

	
	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		msgWhat = 1;
		mReader.reRresh();
		initBookPageFactory();
	}
	
	public void onNewIntent0(Intent intent){
		// TODO Auto-generated method stub
		msgWhat = 1;
		initBookPageFactory();
	}

	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stubd
		mBaseBook.mLastTime = ""+System.currentTimeMillis();
		mBaseBook.mBookMarksNumber = BookStore.getInstance().getBookMarks(this, mBaseBook.mBookId).size();
		BookDao.getInstance().updateBook(this, mBaseBook);
		ReaderSet.getInstance().commitReaderSet();
		super.onPause();
	}
	

	private void initBookPageFactory(){
		new Thread(new mThread()).start();
	}
	
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int v_id = v.getId();
		switch (v_id) {
		case R.id.reader:
			//点击阅读中
			break;
		case 0:
			break;

		default:
			break;
		}
	}
	private boolean isFullScreen = true;
	
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		Log.e("", "onStart");
		mReader.destory();
		super.onDestroy();
	}
	
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}
	
	private void changeReadModel() {
		boolean isYe = ReaderSet.getInstance().getReadModel();
		if (isYe) {
			// 夜间模式
			mReader.setReaderBg(R.drawable.wallpaper7, 0xffffffff);
		} else {
			// 普通模式
			mReader.setReaderBg(ReaderSet.getInstance().getReadBg(), ReaderSet
					.getInstance().getFontColor());
		}

	}

	
	@Override
	public void onCmdHandle(int cmd) {
		mDiffuseView.setVisibility(View.VISIBLE);
	}
	
	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
	}
	
}
